package org.yzh.rbac.controller;

import io.swagger.annotations.Api;
import org.sample.commons.lang.StrUtils;
import org.sample.component.mybatis.Page;
import org.sample.model.APIResult;
import org.sample.model.PageInfo;
import org.sample.model.Pagination;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.yzh.rbac.model.entity.UserDO;
import org.yzh.rbac.service.UserService;

import java.time.LocalDateTime;

@Api(description = "用户API")
@RequestMapping("user")
@RestController
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping
    public Pagination<UserDO> list(UserDO query, PageInfo pageInfo) {
        Pagination result = Page.start(() -> userService.find(query), pageInfo);
        return result;
    }

    @GetMapping("detail")
    public UserDO detail(@RequestParam Integer id) {
        UserDO result = userService.get(id);
        return result;
    }

    @PostMapping
    public APIResult<Boolean> add(UserDO entity) {
        entity.setCreateTime(LocalDateTime.now());
        int row = userService.add(entity);
        return new APIResult(row > 0);
    }

    @PutMapping
    public APIResult<Boolean> update(UserDO entity) {
        int row = userService.update(entity);
        return new APIResult(row > 0);
    }

    @DeleteMapping
    public APIResult<Boolean> delete(@RequestParam String id) {
        int[] ids = StrUtils.toInts(id, ",");
        for (int i : ids)
            userService.delete(i);
        return APIResult.SUCCESS;
    }
}